/* chimaera_user_index-table.c : store the access condition of files
 *
 * ====================================================================
 * Copyright (c) 2008-2009 Chimaera team.  All rights reserved.
 *
 *
 * @author kkndyu
 * @mail kkndyu@gmail.com
 * ====================================================================
 */

#include "bdb_compat.h"
#include "svn_fs.h"
#include "svn_pools.h"
#include "../fs.h"
#include "../err.h"
#include "../util/skel.h"
#include "../util/fs_skels.h"
#include "../../libsvn_fs/fs-loader.h"
#include "bdb-err.h"
#include "dbt.h"
#include "rev-table.h"
#include "../trail.h"

#include "svn_private_config.h"
#include "private/svn_fs_util.h"

#include "chimaera_user_index-table.h"


/* Opening/creating the 'chimaera_file' table.  */

int svn_fs_bdb__open_chimaera_user_index_table(DB **chimaeraui,
                                     DB_ENV *env,
                                     svn_boolean_t create)
{
  const u_int32_t open_flags = (create ? (DB_CREATE | DB_EXCL) : 0);
  DB *chimaera_user_index;

  BDB_ERR(svn_fs_bdb__check_version());
  BDB_ERR(db_create(&chimaera_user_index, env, 0));

  BDB_ERR((chimaera_user_index->open)(
					SVN_BDB_OPEN_PARAMS(chimaera_user_index, NULL),
								"chimaera_user_index", 0, DB_BTREE,
								open_flags, 0666));

  *chimaeraui = chimaera_user_index;
  return 0;
}



/* Storing and retrieving filesystem revisions.  */


svn_error_t *
svn_fs_bdb__get_chimaera_user_index(apr_int32_t *user_recno,
					svn_string_t *userid,  svn_fs_t *fs, apr_pool_t *pool)
{
  base_fs_data_t *bfd = fs->fsap_data;
  int db_err;
  DBT key, value;

  if (userid!=NULL)
  {
	  svn_fs_base__set_dbt(&key, userid->data, userid->len),
      svn_fs_base__result_dbt(&value),
		

	  db_err = bfd->chimaera_user_index->get(
								bfd->chimaera_user_index,
								NULL, &key, &value, 0);

	  svn_fs_base__track_dbt(&value, pool);

	  if (db_err == DB_NOTFOUND)
		  return svn_error_create(9999,NULL,_("userid not exist!"));

	  *user_recno = *(apr_int32_t *)value.data;
  }

  return SVN_NO_ERROR;
}


svn_error_t *
svn_fs_bdb__put_chimaera_user_index(apr_int32_t *user_recno,
				svn_string_t *userid, svn_fs_t *fs, 
				DB_TXN *txn,apr_pool_t *pool)
{
  base_fs_data_t *bfd = fs->fsap_data;
  DBT key, value;

  svn_fs_base__set_dbt(&key, userid->data, userid->len);
  svn_fs_base__set_dbt(&value, user_recno, sizeof(*user_recno));

  SVN_ERR(BDB_WRAP(fs, _("storing message index"),
	  bfd->chimaera_user_index->put(bfd->chimaera_user_index, txn,
	  &key, &value, 0)));
  
  return SVN_NO_ERROR;
}
